<template>
  <div class="home">
    <el-container>
      <el-header class="layout-header">
        <h1>Personal个人工具</h1>
        <el-popover placement="bottom" trigger="hover" v-if="user">
          <div>
            <!-- 个人信息内容 -->
            <div style="display: flex; flex-direction: column; align-items: center;">
              <p>
                <el-button type="primary" @click="showUserInfoDialog" round class="centered-button">
                  个人信息
                </el-button>
              </p>
              <p>
                <el-button type="primary" @click="showUpdateUserInfoDialog" round class="centered-button">
                  修改信息
                </el-button>
              </p>
              <p v-if="user.userType === 0">
                <el-button type="primary" @click="goToAdminPage" round class="centered-button">
                  &nbsp;&nbsp;管理员&nbsp;&nbsp;
                </el-button>
              </p>
              <p>
                <el-button type="danger" @click="logout" round class="centered-button">退出登录</el-button>
              </p>

            </div>
          </div>
          <!-- 头像 -->
          <img class="avatar" :src="avatarUrl" alt="Avatar" slot="reference"/>
        </el-popover>
      </el-header>
      <el-container class="layout-body">
        <el-aside width="200px" class="layout-aside">
          <el-menu :default-active="$router.currentRoute.path" class="el-menu-vertical-demo"
                   background-color="#47698a" text-color="#fff" router active-text-color="#ffd04b">
            <el-submenu>
              <template slot="title">
                <i class="el-icon-date"></i>
                <span>日程日志</span>
                <el-badge is-dot :hidden="ishiddenbadge" class="item"></el-badge>
              </template>
              <el-menu-item-group>
                <el-menu-item index="/schedule">
                  <i class="el-icon-caret-right"></i>
                  <span>日程信息列表</span>
                  <el-badge is-dot :hidden="ishiddenbadge" class="item"></el-badge>
                </el-menu-item>
                <el-menu-item index="/schedule/add">
                  <i class="el-icon-caret-right"></i>
                  <span>添加日程信息</span>
                </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="/note">
              <template slot="title">
                <i class="el-icon-notebook-2"></i>
                <span>我的笔记</span>
              </template>
              <el-menu-item index="/note/add">
                <i class="el-icon-circle-plus"></i>
                <span slot="title">添加笔记</span>
              </el-menu-item>
              <el-menu-item index="/note/list">
                <i class="el-icon-circle-plus"></i>
                <span slot="title">笔记列表</span>
              </el-menu-item>
            </el-submenu>
            <el-menu-item index="/files">
              <i class="el-icon-folder"></i>
              <span slot="title">我的文件</span>
            </el-menu-item>
            <!-- 图片压缩导航-->
            <el-menu-item index="/image">
              <i class="el-icon-picture"></i>
              <span slot="title">图片压缩</span>
            </el-menu-item><!-- 视频转音频导航-->
            <el-menu-item index="/audio">
              <i class="el-icon-film"></i>
              <span slot="title">音频转换</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-main class="layout-main">
          <router-view/>
        </el-main>
      </el-container>
    </el-container>

    <!-- 用户信息弹框 -->
    <el-dialog
        title="个人信息"
        :visible="userInfoDialogVisible"
        @close="closeUserInfoDialog"
        width="30%"
    >
      <div class="user-info-container">
        <!-- 用户头像 -->
        <div class="avatar-container">
          <el-avatar :src="avatarUrl" :style="{ width: '120px', height: '120px' }"></el-avatar>
        </div>

        <!-- 用户信息 -->
        <div class="info-container">
          <div class="info-item">
            <span class="info-label">用户ID：</span>
            <span class="info-value">{{ user.userId }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">用户名：</span>
            <span class="info-value">{{ user.userName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">邮&nbsp;&nbsp;&nbsp;&nbsp;箱：</span>
            <span class="info-value">{{ userInfo.email }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">手机号：</span>
            <span class="info-value">{{ userInfo.phone }}</span>
          </div>
        </div>
      </div>
      <!-- 弹框底部按钮 -->
      <span slot="footer" class="dialog-footer">
      <el-button @click="closeUserInfoDialog">取消</el-button>
    </span>
    </el-dialog>


    <!-- 更改用户信息弹框 -->
    <el-dialog
        title="更改信息"
        :visible="updateUserInfoDialogVisible"
        @close="closeUpdateUserInfoDialog"
    >
      <div class="user-info-container">
        <!-- 用户头像 -->
        <div class="avatar-container">
<!--          <el-avatar :src="avatarUrl" :style="{ width: '120px', height: '120px' }"></el-avatar>-->
          <el-upload
              class="avatar-uploader"
              action="/api/users/uploadAvatar"
              name="multipartFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <el-avatar :src="avatarUrl" :style="{ width: '120px', height: '120px' }"></el-avatar>

          </el-upload>
        </div>

        <!-- 更新用户信息表单 -->
        <el-form ref="userInfoForm" :model="userInfo" :rules="rules" label-width="100px" >
          <el-form-item label="用户ID" >
            <el-input v-model="userInfo.userId" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="userInfo.userName" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userInfo.phone"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="userInfo.newPassword"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="userInfo.confirmPassword"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- 弹框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeUpdateUserInfoDialog">取消</el-button>
        <el-button type="primary" @click="submitUserInfoForm('userInfoForm')">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data: function () {
    return {
      // ====================================schedule模块====================================
      tableData: [],
      ishiddenbadge: true,
      // ====================================user模块====================================
      user: localStorage.getItem('user') ? JSON.parse(localStorage.user) : null,
      avatarUrl: "",
      visible: false,
      userInfoDialogVisible: false, // 控制用户信息弹框的显示与隐藏
      updateUserInfoDialogVisible: false,  // 控制更新用户信息弹框的显示与隐藏
      isChecked: false,
      userInfo: {
        userId: '',
        userName: '',
        password: '',
        email: '',
        phone: '',
        avatarUrl: '',
        newPassword: '',
        confirmPassword: '',
      },
      rules: {
        newPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请再次输入密码', trigger: 'blur'},
          {min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入有效的手机号码', trigger: ['blur', 'change'] }
        ]
      },
    }
  },
  methods: {
    // ====================================schedule模块====================================
    loadingList() {
      this.user = localStorage.getItem('user') ? JSON.parse(localStorage.user) : null;
      // 5，在页面加载时根据showList请求获取数据库的一组数据进行展示
      this.axios.get("/api/schedule/showList/" + this.user.userId + "/getUserScheduleList").then((response) => {
        this.tableData = response.data.data;
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].reminderTime != null) {
            let reminderTime = new Date(this.tableData[i].reminderTime);
            let timeDiff;
            if (this.tableData[i + 1] != undefined) {
              if (this.tableData[i].reminderTime == this.tableData[i + 1].reminderTime) {
                timeDiff = reminderTime.getTime() - (Date.now() + 1000);
              } else {
                timeDiff = reminderTime.getTime() - Date.now();
              }
            } else {
              timeDiff = reminderTime.getTime() - Date.now();
            }
            setTimeout(() => {
              this.ishiddenbadge = false;
              this.reminder('提醒内容：' + this.tableData[i].scheduleContent, '提醒时间：' + this
                  .tableData[i].reminderTime)
            }, timeDiff);
          }
        }
      })
    },
    reminder(title, msg) {
      this.$notify({
        title: title,
        message: msg,
        type: 'success',
        duration: 0
      })
    },
    // ====================================user模块====================================
    logout() {
      // 处理退出登录的逻辑
      //发请求退出登录
      this.axios.get("/api/users/logout").then(response => {
        localStorage.clear();//清空登录成功时保存的数据
        // location.href = "/";
        this.$router.push('/login');
      })
    },
    goToAdminPage() {
      // 处理跳转到管理员页面的逻辑
      this.$router.push('/admin');
    },
    showUserInfoDialog() {
      this.axios.get(`/api/users/${this.user.userId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.userInfo = response.data.data;
              this.userInfoDialogVisible = true;
            } else {
              this.$message.error(response.data.message);
            }
          })
          .catch(error => {
            this.$message.error('获取用户信息失败');
          });
    },
    closeUserInfoDialog() {
      // 关闭用户信息弹框
      this.userInfoDialogVisible = false;
    },


    showUpdateUserInfoDialog() {
      this.axios.get(`/api/users/${this.user.userId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.userInfo = response.data.data;
            } else {
              this.$message.error(response.data.message);
            }
          })
          .catch(error => {
            this.$message.error('获取用户信息失败');
          });
      this.updateUserInfoDialogVisible = true;
    },
    closeUpdateUserInfoDialog() {
      // 关闭更新用户信息弹框
      this.updateUserInfoDialogVisible = false;
    },
    handleAvatarSuccess(response, file) {
      this.avatarUrl = "/api" + response.data;
      this.user.avatarUrl = response.data;
      localStorage.user = JSON.stringify(this.user);
      this.$message.success('头像上传成功');
    },
    beforeAvatarUpload(file) {
      const allowedExtensions = ['jpg', 'jpeg', 'png']; // 允许的文件扩展名
      const allowedSize = 2 * 1024 * 1024; // 允许的文件大小（2MB）

      const extension = file.name.split('.').pop().toLowerCase(); // 获取文件的扩展名
      const fileSize = file.size; // 获取文件的大小

      // 检查文件扩展名是否合法
      const isValidExtension = allowedExtensions.includes(extension);
      if (!isValidExtension) {
        this.$message.error('只允许上传jpg、jpeg和png格式的图片');
        return false; // 返回false，阻止上传
      }

      // 检查文件大小是否超过限制
      const isValidSize = fileSize <= allowedSize;
      if (!isValidSize) {
        this.$message.error('文件大小不能超过2MB');
        return false; // 返回false，阻止上传
      }

      return true; // 返回true，允许上传
    },
    submitUserInfoForm(userInfoForm){
      this.$refs[userInfoForm].validate((valid) => {
        if (valid) {
          const updatedUserInfo = {
            email: this.userInfo.email,
            phone: this.userInfo.phone,
            password: this.userInfo.newPassword,
          };
          const newPassword =  this.userInfo.newPassword;
          const confirmPassword =  this.userInfo.confirmPassword;
          if(newPassword !== confirmPassword){
            this.$message.error('两次输入的密码不一致');
            return;
          }


          this.axios.put(`/api/users/${this.userInfo.userId}`, updatedUserInfo)
              .then(response => {
                if (response.data.code === 204) {
                  this.$message.success('更新信息成功');
                  this.user.email = this.userInfo.email;
                  this.user.phone = this.userInfo.phone;
                  this.user.password = this.userInfo.password;
                  localStorage.user = JSON.stringify(this.user);

                } else {
                  this.$message.error(response.data.message);
                }
              })
              .catch(error => {
                this.$message.error('更新信息失败');
              });

        }
      });

    }


  },
  mounted() {
    // ====================================schedule模块====================================
    this.loadingList();
    this.$router.beforeEach((to, from, next) => {
      if (to.path === '/schedule') {
        this.ishiddenbadge = true; // 点击日程日志菜单项时，将ishiddenbadge的值设置为true，即隐藏el-badge
      }else if(from.path === '/schedule'){
          this.ishiddenbadge = true;
      }
      next();
    });
    // ====================================user模块====================================
    this.avatarUrl = "/api" + this.user.avatarUrl;
    console.log(this.avatarUrl)

  }
}
</script>

<style>
.layout-header {
  line-height: 60px;
  color: #FFF;
  background: #2c3e50;
}

.layout-body {
  position: absolute;
  top: 60px;
  bottom: 0;
  right: 0;
  left: 0;
}

.layout-aside {
  background: #47698a;
}

.layout-aside .el-menu {
  border: 0;
}

.item {
  padding-bottom: 12px;
}

.layout-main {
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  cursor: pointer;
  position: absolute;
  top: 5px;
  /* 调整位置以适应头像 */
  right: 20px;
  /* 调整位置以适应头像 */
}

.centered-button {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 8px 0;
}

.user-info-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  margin-bottom: 30px;
}



.avatar-container {
  margin-bottom: 20px;
}

.info-container {
  width: 100%;
}

.info-item {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px 0;
  text-align: center; /* 将信息项内容居中对齐 */
}

.info-label {
  font-weight: bold;
  width: 40%;
  text-align: right; /* 将标签内容右对齐 */
  margin-right: 10px;
  font-size: 18px;
}

.info-value {
  width: 60%;
  text-align: left; /* 将值内容左对齐 */
  font-size: 18px;
}


.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>